<?php

declare(strict_types=1);
/**
 * Created by .
 * User: luogan
 * Date: 2021/12/22
 */

namespace App\Service;

use App\Exception\ErrorException;
use App\Model\Admin;
use App\Model\AdminLoginLog;
use Hyperf\Di\Annotation\Inject;
use HyperfExt\Jwt\Contracts\JwtFactoryInterface;
use ipip\datx\City;
use Jenssegers\Agent\Agent;
use Hyperf\DbConnection\Db;
class UserService
{

    /**
     * @Inject
     * @var JwtFactoryInterface
     */
    private $jwtFactoryInterface;


    /**
     * @Inject
     * @var AuthMenuService
     */
    private $authMenuService;

    /**
     * 登录
     * @param string $username
     * @param string $password
     * @return string
     */
    public function login(string $username, string $password):array
    {
        $admin = Admin::query()->where('username', $username)->first();
        if (!$admin) {
            throw new ErrorException('账户不存在');
        }
        if ($admin['status'] == 1) {
            throw new ErrorException('账户已禁用');
        }
        $pwd = md5($admin['salt'] . $password);
        if (!hash_equals($admin['password'], $pwd)) {
            throw new ErrorException('账号或密码错误');
        }
        $data['last_login_time'] = time();
        $data['last_login_ip'] = get_client_ip();
        Db::beginTransaction();
        try{
            $admin->fillable(['last_login_time', 'last_login_ip'])->fill($data)->save();
            //登录记录
            $this->adminLoginLog($admin['id'],$admin['username'],$data['last_login_ip']);
            Db::commit();
        } catch(\Throwable $ex){
            Db::rollBack();
            throw new ErrorException('登录失败！');
        }
        //生成token
        $jwt = $this->jwtFactoryInterface->make();
        $strToken = $jwt->fromUser($admin);
        //生成菜单权限缓存
        $this->authMenuService->init($admin['id']);
        return ['admin' => $admin, 'token' => $strToken];
    }

    /**
     * 管理员退出
     * @return \HyperfExt\Jwt\Jwt
     * @throws \HyperfExt\Jwt\Exceptions\JwtException
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function logout()
    {
        $result = jwt()->invalidate();

        return $result;
    }


   /* public function refresh()
    {
        $result = jwt()->refresh();
        return ['token' => $result];
    }*/

    /**
     * 生成登录记录
     * @param $adminId
     * @param $username
     * @param $ip
     * @param $remark
     * @return AdminLoginLog|\Hyperf\Database\Model\Model
     */
    public function adminLoginLog($adminId,$username,$ip,$remark='登录成功')
    {
        $agent = new Agent();
        $user_agent = request()->getHeader('user-agent');
        $agent->setUserAgent($user_agent[0]);
        $agent->is('Windows');
        //获取浏览器
        $browser = $agent->browser();
        //获取浏览器版本
        $browser_version = intval($agent->version($browser));
        //获取操作系统
        $platform = $agent->platform();
        //获取操作系统版本
        $platform_version = intval($agent->version($platform));
        // 城市级数据库
        $bs =  new City(BASE_PATH . '/public/ipdata/17monipdb.datx');
        $address = $bs->find($ip);
        $reg['ip_province'] = isset($address[1]) ? $address[1] : '';
        $reg['ip_city'] = isset($address[2]) ? $address[2] : '';
        $reg['ip_address'] = implode(" ", $address);
        $region = $reg['ip_province'] . ' ' . $reg['ip_city'] . ' ' . $reg['ip_address'];
        $log = AdminLoginLog::create([
            'admin_id' => $adminId,
            'admin_name' => $username,
            'ip' =>$ip,
            'browser' => $browser . ' ' . $browser_version,
            'system' => $platform . '' . $platform_version,
            'region' => $region,
            'remark' =>$remark,
        ]);
        return $log;
    }




}
